import { Router, Request, Response } from "express";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { IUserDocument, User } from "../models/user.model";
import { authenticateToken } from "../middleware/auth.middleware";
import { EnumStatusCode } from "@shared/constant/enum";
import { requestLogger } from "../logger/logger";

export const authRouter = Router();

const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";

// 管理员登录
authRouter.post("/login",requestLogger, async (req: Request, res: Response) => {
  try {
    const { username, password, phone } = req.body;

    if (!password || (!username && !phone)) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "请提供用户名/手机号和密码",
        data: null,
      });
    }

    // 查找用户（支持用户名或手机号登录）
    const query = username ? { username } : { phone };
    const user = await User.findOne(query);

    if (!user) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "用户不存在",
        data: null,
      });
    }

    // 检查账户状态
    if (user.status === "disabled") {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "账户已被禁用",
        data: null,
      });
    }

    // 验证密码（暂时直接比较，后续需要加密）
    // const isPasswordValid = await bcrypt.compare(password, user.password);
    const isPasswordValid = password === user.password;

    if (!isPasswordValid) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "密码错误",
        data: null,
      });
    }

    // 生成JWT token
    const token = jwt.sign(
      {
        userId: user._id,
        username: user.username,
        role: user.role,
      },
      JWT_SECRET,
      { expiresIn: "24h" }
    );

    // 返回用户信息（不包含密码）
    const userInfo = {
      id: user._id,
      username: user.username,
      phone: user.phone,
      role: user.role,
      status: user.status,
      create_time: user.create_time,
    };

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "登录成功",
      data: {
        user: userInfo,
        token,
        expires_in: 24 * 60 * 60 * 1000, // 24小时（毫秒）
      },
    });
  } catch (error) {
    console.error("登录失败:", error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "登录失败",
      data: null,
    });
  }
});

// 用户注册
authRouter.post("/register",requestLogger, async (req: Request, res: Response) => {
  try {
    const { username, password, phone } = req.body;

    // 验证必填字段
    if (!username || !password || !phone) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "用户名、密码和手机号不能为空",
        data: null,
      });
    }

    // 检查手机号是否已存在
    const existingUser = await User.findOne({ phone });
    if (existingUser) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "手机号已被注册",
        data: null,
      });
    }

    // 加密密码（暂时跳过）
    // const hashedPassword = await bcrypt.hash(password, 10);

    // 创建用户
    const user = new User({
      username,
      password, // 后续需要使用 hashedPassword
      phone,
      role: "user", // 注册的用户默认为普通用户
      status: "active",
    });

    const savedUser = await user.save();

    // 生成JWT token
    const token = jwt.sign(
      {
        userId: savedUser._id,
        username: savedUser.username,
        role: savedUser.role,
      },
      JWT_SECRET,
      { expiresIn: "24h" }
    );

    // 返回用户信息（不包含密码）
    const userInfo = {
      id: savedUser._id,
      username: savedUser.username,
      phone: savedUser.phone,
      role: savedUser.role,
      status: savedUser.status,
      create_time: savedUser.create_time,
    };

    res.status(EnumStatusCode.CREATED).json({
      code: EnumStatusCode.CREATED,
      message: "注册成功",
      data: {
        user: userInfo,
        token,
        expires_in: 24 * 60 * 60 * 1000,
      },
    });
  } catch (error) {
    console.error("注册失败:", error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "注册失败",
      data: null,
    });
  }
});

// 登出
authRouter.post("/logout", requestLogger, async (req: Request, res: Response) => {
  // JWT是无状态的，登出主要在前端处理（删除token）
  // 这里可以记录登出日志或处理其他逻辑
  res.json({
    code: EnumStatusCode.SUCCESS,
    message: "登出成功",
    data: null,
  });
});

// 刷新token（需要鉴权）
authRouter.post(
  "/refresh",
  authenticateToken,
  async (req: Request, res: Response) => {
    try {
      const { token } = req.body;

      if (!token) {
        return res.status(EnumStatusCode.BAD_REQUEST).json({
          code: EnumStatusCode.BAD_REQUEST,
          message: "Token不能为空",
          data: null,
        });
      }

      // 从中间件获取用户信息
      const user = req.user;

      // 检查用户是否仍然存在且状态正常
      const currentUser = await User.findById(user?.user_id);
      if (!currentUser || currentUser.status === "disabled") {
        return res.status(EnumStatusCode.UNAUTHORIZED).json({
          code: EnumStatusCode.UNAUTHORIZED,
          message: "用户不存在或已被禁用",
          data: null,
        });
      }

      // 生成新的token
      const newToken = jwt.sign(
        {
          userId: currentUser._id,
          username: currentUser.username,
          role: currentUser.role,
        },
        JWT_SECRET,
        { expiresIn: "24h" }
      );

      res.json({
        code: EnumStatusCode.SUCCESS,
        message: "Token刷新成功",
        data: {
          token: newToken,
          expires_in: 24 * 60 * 60 * 1000,
        },
      });
    } catch (error) {
      console.error("刷新token失败:", error);
      res.status(EnumStatusCode.UNAUTHORIZED).json({
        code: EnumStatusCode.UNAUTHORIZED,
        message: "Token无效",
        data: null,
      });
    }
  }
);

// 修改密码（需要鉴权）
authRouter.post(
  "/change-password",
  [authenticateToken,requestLogger],
  async (req: Request, res: Response) => {
    try {
      const { oldPassword, newPassword } = req.body;

      if (!oldPassword || !newPassword) {
        return res.status(EnumStatusCode.BAD_REQUEST).json({
          code: EnumStatusCode.BAD_REQUEST,
          message: "原密码和新密码不能为空",
          data: null,
        });
      }

      // 从中间件获取用户信息
      const currentUser = (req as any).user;

      console.log("currentUser", currentUser);

      // 查找用户
      const user = await User.findById(currentUser.user_id);
      if (!user) {
        return res.status(EnumStatusCode.NOT_FOUND).json({
          code: EnumStatusCode.NOT_FOUND,
          message: "用户不存在",
          data: null,
        });
      }

      // 验证原密码
      // const isOldPasswordValid = await bcrypt.compare(oldPassword, user.password);
      const isOldPasswordValid = oldPassword === user.password;

      if (!isOldPasswordValid) {
        return res.status(EnumStatusCode.BAD_REQUEST).json({
          code: EnumStatusCode.BAD_REQUEST,
          message: "原密码错误",
          data: null,
        });
      }

      // 更新密码
      // const hashedNewPassword = await bcrypt.hash(newPassword, 10);
      user.password = newPassword; // 后续需要使用 hashedNewPassword
      await user.save();

      res.json({
        code: EnumStatusCode.SUCCESS,
        message: "密码修改成功",
        data: null,
      });
    } catch (error) {
      console.error("修改密码失败:", error);
      res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
        code: EnumStatusCode.INTERNAL_SERVER_ERROR,
        message: "修改密码失败",
        data: null,
      });
    }
  }
);

// 获取当前用户信息（需要鉴权）
authRouter.get(
  "/me",
  [authenticateToken,requestLogger],
  async (req: Request, res: Response) => {
    try {
      const currentUser = (req as any).user;

      // 查找用户最新信息
      const user = await User.findById(currentUser.userId).select("-password");
      if (!user) {
        return res.status(EnumStatusCode.NOT_FOUND).json({
          code: EnumStatusCode.NOT_FOUND,
          message: "用户不存在",
          data: null,
        });
      }

      const userInfo = {
        id: user._id,
        username: user.username,
        phone: user.phone,
        role: user.role,
        status: user.status,
        create_time: user.create_time,
      };

      res.json({
        code: EnumStatusCode.SUCCESS,
        message: "获取用户信息成功",
        data: userInfo,
      });
    } catch (error) {
      console.error("获取用户信息失败:", error);
      res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
        code: EnumStatusCode.INTERNAL_SERVER_ERROR,
        message: "获取用户信息失败",
        data: null,
      });
    }
  }
);
